import request from '@/utils/request'

const state = {
  // 反馈数据
  feedbacks: [],
  totalFeedbacks: 0,
  
  // 网格员数据
  gridMembers: [],
  totalGridMembers: 0,
  
  // 统计数据
  statistics: [],
  dashboardData: {},
  
  // 分页信息
  pagination: {
    currentPage: 1,
    pageSize: 10,
    total: 0
  }
}

const mutations = {
  SET_FEEDBACKS: (state, data) => {
    state.feedbacks = data.list || data
    state.totalFeedbacks = data.total || data.length
  },
  SET_GRID_MEMBERS: (state, data) => {
    state.gridMembers = data.list || data
    state.totalGridMembers = data.total || data.length
  },
  SET_STATISTICS: (state, data) => {
    state.statistics = data
  },
  SET_DASHBOARD_DATA: (state, data) => {
    state.dashboardData = data
  },
  SET_PAGINATION: (state, pagination) => {
    state.pagination = { ...state.pagination, ...pagination }
  },
  ADD_FEEDBACK: (state, feedback) => {
    state.feedbacks.unshift(feedback)
    state.totalFeedbacks++
  },
  UPDATE_FEEDBACK: (state, feedback) => {
    const index = state.feedbacks.findIndex(item => item.id === feedback.id)
    if (index !== -1) {
      state.feedbacks.splice(index, 1, feedback)
    }
  },
  DELETE_FEEDBACK: (state, feedbackId) => {
    const index = state.feedbacks.findIndex(item => item.id === feedbackId)
    if (index !== -1) {
      state.feedbacks.splice(index, 1)
      state.totalFeedbacks--
    }
  }
}

const actions = {
  // 获取反馈列表
  async getFeedbacks({ commit, rootGetters }, params = {}) {
    try {
      const userRole = rootGetters['user/userRole']
      let url = ''
      
      switch (userRole) {
        case 'ADMIN':
          url = '/api/admin/feedbacks'
          if (params.state !== undefined) {
            url += `/state/${params.state}`
          }
          break
        case 'GRID_MEMBER':
          url = params.processed ? '/api/grid/feedbacks/processed' : '/api/grid/feedbacks/assigned'
          break
        case 'SUPERVISOR':
          url = '/api/supervisor/feedback/history'
          break
        default:
          throw new Error('无效的用户角色')
      }
      
      const response = await request.get(url, { params })
      const { data } = response
      
      if (data.code === 200) {
        commit('SET_FEEDBACKS', data.data)
        return data.data
      } else {
        throw new Error(data.message)
      }
    } catch (error) {
      throw error
    }
  },

  // 提交反馈
  async submitFeedback({ commit, rootGetters }, feedbackData) {
    try {
             const response = await request.post('/api/supervisor/feedback', feedbackData)
      const { data } = response
      
      if (data.code === 200) {
        commit('ADD_FEEDBACK', data.data)
        return data.data
      } else {
        throw new Error(data.message)
      }
    } catch (error) {
      throw error
    }
  },

  // 分配反馈给网格员
  async assignFeedback({ commit }, { feedbackId, gmId }) {
    try {
             const response = await request.post(`/api/admin/feedbacks/${feedbackId}/assign`, { gmId })
      const { data } = response
      
      if (data.code === 200) {
        commit('UPDATE_FEEDBACK', data.data)
        return data.data
      } else {
        throw new Error(data.message)
      }
    } catch (error) {
      throw error
    }
  },

  // 确认AQI数据
  async confirmAQIData({ commit }, { feedbackId, aqiData }) {
    try {
             const response = await request.post(`/api/grid/feedbacks/${feedbackId}/confirm`, aqiData)
      const { data } = response
      
      if (data.code === 200) {
        commit('UPDATE_FEEDBACK', data.data)
        return data.data
      } else {
        throw new Error(data.message)
      }
    } catch (error) {
      throw error
    }
  },

  // 获取网格员列表
  async getGridMembers({ commit }, params = {}) {
    try {
             const response = await request.get('/api/admin/grid-members/available', { params })
      const { data } = response
      
      if (data.code === 200) {
        commit('SET_GRID_MEMBERS', data.data)
        return data.data
      } else {
        throw new Error(data.message)
      }
    } catch (error) {
      throw error
    }
  },

  // 获取统计数据
  async getStatistics({ commit, rootGetters }, params = {}) {
    try {
      const userRole = rootGetters['user/userRole']
      let url = ''
      
      switch (userRole) {
        case 'ADMIN':
          url = '/api/admin/statistics/system'
          break
        case 'GRID_MEMBER':
          url = '/api/grid/statistics'
          break
        case 'SUPERVISOR':
          url = '/api/supervisor/feedback/statistics'
          break
        default:
          throw new Error('无效的用户角色')
      }
      
      const response = await request.get(url, { params })
      const { data } = response
      
      if (data.code === 200) {
        commit('SET_STATISTICS', data.data)
        return data.data
      } else {
        throw new Error(data.message)
      }
    } catch (error) {
      throw error
    }
  },

  // 获取仪表板数据
  async getDashboardData({ commit, dispatch, rootGetters }) {
    try {
      const userRole = rootGetters['user/userRole']
      let dashboardData = {}
      
      switch (userRole) {
        case 'ADMIN':
          // 管理员仪表板数据
                     const [systemStats, monthlyStats, aqiStats] = await Promise.all([
             request.get('/api/admin/statistics/system'),
             request.get('/api/admin/statistics/monthly'),
             request.get('/api/admin/statistics/aqi-by-region')
           ])
          
          dashboardData = {
            systemStats: systemStats.data.data,
            monthlyStats: monthlyStats.data.data,
            aqiStats: aqiStats.data.data
          }
          break
          
        case 'GRID_MEMBER':
          // 网格员仪表板数据
                     const [assignedFeedbacks, workStats] = await Promise.all([
             request.get('/api/grid/feedbacks/assigned'),
             request.get('/api/grid/statistics')
           ])
          
          dashboardData = {
            assignedFeedbacks: assignedFeedbacks.data.data,
            workStats: workStats.data.data
          }
          break
          
        case 'SUPERVISOR':
          // 公众监督员仪表板数据
                     const [feedbackHistory, feedbackStats] = await Promise.all([
             request.get('/api/supervisor/feedback/history'),
             request.get('/api/supervisor/feedback/statistics')
           ])
          
          dashboardData = {
            feedbackHistory: feedbackHistory.data.data,
            feedbackStats: feedbackStats.data.data
          }
          break
      }
      
      commit('SET_DASHBOARD_DATA', dashboardData)
      return dashboardData
    } catch (error) {
      throw error
    }
  }
}

const getters = {
  feedbacks: state => state.feedbacks,
  totalFeedbacks: state => state.totalFeedbacks,
  gridMembers: state => state.gridMembers,
  totalGridMembers: state => state.totalGridMembers,
  statistics: state => state.statistics,
  dashboardData: state => state.dashboardData,
  pagination: state => state.pagination,
  
  // 根据状态获取反馈
  getFeedbacksByState: state => status => {
    return state.feedbacks.filter(feedback => feedback.state === status)
  },
  
  // 根据ID获取反馈
  getFeedbackById: state => id => {
    return state.feedbacks.find(feedback => feedback.id === id)
  },
  
  // 根据ID获取网格员
  getGridMemberById: state => id => {
    return state.gridMembers.find(member => member.gmId === id)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 